package com.rc.web.service.impl;

import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.rc.common.constant.Code;
import com.rc.common.exception.BusinessException;
import com.rc.pojo.dto.knowledge.KnowLedgeAddDTO;
import com.rc.pojo.dto.knowledge.KnowLedgeUpdateDTO;
import com.rc.pojo.dto.knowledge.KnowledgePageQuery;
import com.rc.pojo.po.Knowledge;
import com.rc.pojo.vo.knowldege.KnowledgePageVO;
import com.rc.pojo.vo.knowldege.KnowledgeVO;
import com.rc.web.converter.KnowledgeConverter;
import com.rc.web.mapper.KnowledgeMapper;
import com.rc.web.service.KnowledgeService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 知识服务实现类
 * 提供知识相关的业务逻辑实现
 */
@Service
@RequiredArgsConstructor
public class KnowledgeServiceImpl extends ServiceImpl<KnowledgeMapper, Knowledge> implements KnowledgeService {
    // 知识转换器
    private final KnowledgeConverter knowledgeConverter;

    /**
     * 根据病虫害ID列表获取知识列表
     * @param illIds 病虫害ID列表
     * @return 知识VO列表
     */
    @Override
    public List<KnowledgeVO> getListByIllIds(List<Long> illIds) {
        // 根据病虫害ID列表查询知识列表
        List<Knowledge> knowledgeList = mapper.selectListByIllIds(illIds);
        // 转换为VO列表并返回
        return knowledgeList.stream()
                .map(knowledgeConverter::toVO)
                .toList();
    }

    /**
     * 分页查询知识
     * @param dto 分页查询条件
     * @return 分页结果
     */
    @Override
    public Page<KnowledgePageVO> getPage(KnowledgePageQuery dto) {
        return mapper.selectPage(dto);
    }

    /**
     * 根据ID删除知识
     * @param id 知识ID
     */
    @Override
    public void deleteById(Long id) {
        mapper.deleteById(id);
    }

    /**
     * 添加知识
     * @param dto 知识添加DTO
     */
    @Override
    public void add(KnowLedgeAddDTO dto) {
        // 转换DTO为PO并保存
        Knowledge knowledge = knowledgeConverter.addDTO2PO(dto);
        this.save(knowledge);
    }

    /**
     * 更新知识
     * @param dto 知识更新DTO
     */
    @Override
    public void updateOneById(KnowLedgeUpdateDTO dto) {
        // 转换DTO为PO并更新
        Knowledge knowledge = knowledgeConverter.updateDTO2PO(dto);

        boolean success = this.updateById(knowledge);
        if (!success){
            throw new BusinessException(Code.APPROVAL);
        }
    }

    /**
     * 根据ID获取知识详情
     * @param id 知识ID
     * @return 知识VO
     */
    @Override
    public KnowledgeVO getOneById(Long id) {
        Knowledge knowledge = mapper.selectOneById(id);
        return knowledgeConverter.toVO(knowledge);
    }
}
